package org.jeecgframework.web.system.controller.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import net.lahuobao.finance.entity.reccode.UserRecCodeEntity;
import net.lahuobao.finance.service.reccode.ReccodeServiceI;
import net.lahuobao.shunting.entity.shunt.DepartVO;
import net.lahuobao.shunting.service.shunt.DepartService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Property;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.dao.jdbc.JdbcDao;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.ComboTree;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.tag.vo.easyui.ComboTreeModel;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.TSUserOrg;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 部门信息处理类
 * 
 * @author 张代浩
 * 
 */
//@Scope("prototype")
@Controller
@RequestMapping("/departController")
public class DepartController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(DepartController.class);
	private UserService userService;
	private SystemService systemService;

	@Autowired
	private ReccodeServiceI reccodeService;
	@Autowired
	private DepartService departService;
	@Autowired
	public void setSystemService(SystemService systemService) {
		this.systemService = systemService;
	}

	public UserService getUserService() {
		return userService;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * 部门列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "depart")
	public ModelAndView depart() {
		return new ModelAndView("system/depart/departList");
	}

	/**
	 * easyuiAJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
		this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除部门：
	 * <ul>
     *     组织机构下存在子机构时
     *     <li>不允许删除 组织机构</li>
	 * </ul>
	 * <ul>
     *     组织机构下存在用户时
     *     <li>不允许删除 组织机构</li>
	 * </ul>
	 * <ul>
     *     组织机构下 不存在子机构 且 不存在用户时
     *     <li>删除 组织机构-角色 信息</li>
     *     <li>删除 组织机构 信息</li>
	 * </ul>
	 * @return 删除的结果信息
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(TSDepart depart, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		depart = systemService.getEntity(TSDepart.class, depart.getId());
        message = MutiLangUtil.paramDelSuccess("common.department");
        if (depart.getTSDeparts().size() == 0) {
            Long userCount = systemService.getCountForJdbc("select count(1) from t_s_user_org where org_id='" + depart.getId() + "'");
            if(userCount == 0) { // 组织机构下没有用户时，该组织机构才允许删除。
                //systemService.executeSql("delete from t_s_role_org where org_id=?", depart.getId());
                //systemService.delete(depart);
				depart.setWorking(0);//修改状态标志以被删除
				systemService.saveOrUpdate(depart);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }else{
				message = "存在用户成员不能删除";
			}
        } else {
            //message = MutiLangUtil.paramDelFail("common.department"); 这个取出来没有说明原因
			message = "存在下级机构不能删除";
        }
        j.setMsg(message);
		return j;
	}


	public void upEntity(TSDepart depart) {
		List<TSUser> users = systemService.findByProperty(TSUser.class, "TSDepart.id", depart.getId());
		if (users.size() > 0) {
			for (TSUser tsUser : users) {
				//tsUser.setTSDepart(null);
				//systemService.saveOrUpdate(tsUser);
				systemService.delete(tsUser);
			}
		}
	}

	/**
	 * 添加部门
	 * 
	 * @param depart
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(TSDepart depart, HttpServletRequest request) {
		String message = null;
		// 设置上级部门
		String pid = request.getParameter("TSPDepart.id");
		if (pid.equals("")) {
			depart.setTSPDepart(null);
		}
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(depart.getId())) {
            message = MutiLangUtil.paramUpdSuccess("common.department");
			userService.saveOrUpdate(depart);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} else {
            message = MutiLangUtil.paramAddSuccess("common.department");
			userService.save(depart);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}

        j.setMsg(message);
		return j;
	}
	@RequestMapping(params = "add")
	public ModelAndView add(TSDepart depart, HttpServletRequest req) {
		List<TSDepart> departList = systemService.getList(TSDepart.class);
		req.setAttribute("departList", departList);
//        这个if代码段没有用吧，注释之
//		if (StringUtil.isNotEmpty(depart.getId())) {
//			TSDepart tspDepart = new TSDepart();
//			TSDepart tsDepart = new TSDepart();
//			depart = systemService.getEntity(TSDepart.class, depart.getId());
//			tspDepart.setId(depart.getId());
//			tspDepart.setDepartname(depart.getDepartname());
//			tsDepart.setTSPDepart(tspDepart);
//			req.setAttribute("depart", tsDepart);
//		}
        req.setAttribute("pid", depart.getId());
		return new ModelAndView("system/depart/depart");
	}
	/**
	 * 部门列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "update")
	public ModelAndView update(TSDepart depart, HttpServletRequest req) {
		List<TSDepart> departList = systemService.getList(TSDepart.class);
		req.setAttribute("departList", departList);
		if (StringUtil.isNotEmpty(depart.getId())) {
			depart = systemService.getEntity(TSDepart.class, depart.getId());
			req.setAttribute("depart", depart);
		}
		return new ModelAndView("system/depart/depart");
	}
	
	/**
	 * 父级权限列表
	 * 
	 * @param request
	 * @param comboTree
	 * @return
	 */
	@RequestMapping(params = "setPFunction")
	@ResponseBody
	public List<ComboTree> setPFunction(HttpServletRequest request, ComboTree comboTree) {
		CriteriaQuery cq = new CriteriaQuery(TSDepart.class);
		if(null != request.getParameter("selfId")){
			cq.notEq("id", request.getParameter("selfId"));
		}
		if (comboTree.getId() != null) {
			cq.eq("TSPDepart.id", comboTree.getId());
		}
		if (comboTree.getId() == null) {
			cq.isNull("TSPDepart");
		}
		cq.add();
		List<TSDepart> departsList = systemService.getListByCriteriaQuery(cq, false);
		List<ComboTree> comboTrees = new ArrayList<ComboTree>();
		ComboTreeModel comboTreeModel = new ComboTreeModel("id", "departname", "TSDeparts");
		comboTrees = systemService.ComboTree(departsList, comboTreeModel, null, true);
		return comboTrees;

	}

	/**
	 * 部门列表，树形展示
	 * @param request
	 * @param response
	 * @param treegrid
	 * @return
	 */
	@RequestMapping(params = "departgrid")
	@ResponseBody
	public Object departgrid(TSDepart tSDepart,HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
		CriteriaQuery cq = new CriteriaQuery(TSDepart.class);
		if("yes".equals(request.getParameter("isSearch"))){
			treegrid.setId(null);
			tSDepart.setId(null);
		} 
		if(null != tSDepart.getDepartname()){
			org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tSDepart);
		}
		if (treegrid.getId() != null) {
			cq.eq("TSPDepart.id", treegrid.getId());
		}
		//added by zoyation,只查询非门店和区域的组织机构
		cq.eq("departType", 0);
		if (treegrid.getId() == null) {
			cq.isNull("TSPDepart");
		}
		cq.add();
		List<TreeGrid> departList =null;
		departList=systemService.getListByCriteriaQuery(cq, false);
		if(departList.size()==0&&tSDepart.getDepartname()!=null){ 
			cq = new CriteriaQuery(TSDepart.class);
			TSDepart parDepart = new TSDepart();
			tSDepart.setTSPDepart(parDepart);
			org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tSDepart);
		    departList =systemService.getListByCriteriaQuery(cq, false);
		}
		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
		TreeGridModel treeGridModel = new TreeGridModel();
		treeGridModel.setTextField("departname");
		treeGridModel.setParentText("TSPDepart_departname");
		treeGridModel.setParentId("TSPDepart_id");
		treeGridModel.setSrc("description");
		treeGridModel.setIdField("id");
		treeGridModel.setChildList("TSDeparts");
        Map<String,Object> fieldMap = new HashMap<String, Object>();
        fieldMap.put("orgCode", "orgCode");
        fieldMap.put("orgType", "orgType");
		fieldMap.put("mobile", "mobile");
		fieldMap.put("fax", "fax");
		fieldMap.put("address", "address");
		fieldMap.put("carrier", "carrier");
		fieldMap.put("service", "service");
		fieldMap.put("dataOwner", "dataOwner");
		fieldMap.put("advance", "advance");
		fieldMap.put("recCode","reccodeEntityecCode");
		fieldMap.put("businessLicense","businessLicense");
		fieldMap.put("organizational","organizational");
		fieldMap.put("legalCard","legalCard");
        treeGridModel.setFieldMap(fieldMap);
        treeGrids = systemService.treegrid(departList, treeGridModel);

        JSONArray jsonArray = new JSONArray();
		String businessRole = "";
        for (TreeGrid treeGrid : treeGrids) {
			businessRole = "";
			if (treeGrid.getFieldMap().get("carrier") != null && treeGrid.getFieldMap().get("carrier").equals("1")){businessRole = "物流服务商";}
			if (treeGrid.getFieldMap().get("service") != null && treeGrid.getFieldMap().get("service").equals("1")){
				if(businessRole.length() > 0){businessRole+=",";}
				businessRole += "承运商";
			}
			if(treeGrid.getFieldMap().get("dataOwner") != null && treeGrid.getFieldMap().get("dataOwner").equals("1")){
				if(businessRole.length() > 0){businessRole+=",";}
				businessRole += "数据主体";
			}
			if(treeGrid.getFieldMap().get("advance") != null && treeGrid.getFieldMap().get("advance").equals("1")){
				if(businessRole.length() > 0){businessRole+=",";}
				businessRole += "运费垫付机构";
			}
			treeGrid.getFieldMap().put("businessRole",businessRole);
			jsonArray.add(JSON.parse(treeGrid.toJson()));
        }
        return jsonArray;
	}
	//----
	/**
	 * 方法描述:  查看成员列表
	 * 作    者： yiming.zhang
	 * 日    期： Dec 4, 2013-8:53:39 PM
	 * @param request
	 * @param departid
	 * @return 
	 * 返回类型： ModelAndView
	 */
	@RequestMapping(params = "userList")
	public ModelAndView userList(HttpServletRequest request, String departid) {
		request.setAttribute("departid", departid);
		return new ModelAndView("system/depart/departUserList");
	}
	
	/**
	 * 方法描述:  成员列表dataGrid
	 * 作    者： yiming.zhang
	 * 日    期： Dec 4, 2013-10:40:17 PM
	 * @param user
	 * @param request
	 * @param response
	 * @param dataGrid 
	 * 返回类型： void
	 */
	@RequestMapping(params = "userDatagrid")
	public void userDatagrid(TSUser user,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TSUser.class, dataGrid);
		//查询条件组装器
//		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, user);
//		String departid = oConvertUtils.getString(request.getParameter("departid"));
//		if (!StringUtil.isEmpty(departid)) {
//
//			DetachedCriteria dc = cq.getDetachedCriteria();
//			DetachedCriteria dcDepart = dc.createCriteria("userOrgList");
//			dcDepart.add(Restrictions.eq("tsDepart.id", departid));
//            // 这种方式也是可以的
////            DetachedCriteria dcDepart = dc.createAlias("userOrgList", "userOrg");
////            dcDepart.add(Restrictions.eq("userOrg.tsDepart.id", departid));
//
//		}
//		Short[] userstate = new Short[] { Globals.User_Normal, Globals.User_ADMIN };
//		cq.in("status", userstate);
//		cq.add();
//		this.systemService.getDataGridReturn(cq, true);

//-------------------------2016-09-01 Lijie修改
		Map<String,Object> serachParams = new HashMap<String, Object>();
		String queryParams_memberName 	= request.getParameter("userName");
		String queryParams_realName 	= request.getParameter("realName");
		String queryParams_recCode 		= request.getParameter("recCode");
		String queryParams_cardedNumber = request.getParameter("cardedNumber");
		String departid 				= oConvertUtils.getString(request.getParameter("departid"));

		String queryParams_sort			= request.getParameter("sort");						//按照谁排序
		String queryParams_order		= request.getParameter("order");					//排序方式
		String queryParams_page			= request.getParameter("page");						//当前页
		String queryParams_rows			= request.getParameter("rows");						//页数大小
		if(queryParams_memberName 	!= null && queryParams_memberName.trim().length() 	> 0){serachParams.put("memberName",queryParams_memberName);}else{serachParams.put("memberName",null);}
		if(queryParams_realName 	!= null && queryParams_realName.trim().length()		> 0){serachParams.put("realName",queryParams_realName);}else{serachParams.put("realName",null);}
		if(queryParams_recCode 		!= null && queryParams_recCode.trim().length() 		> 0){serachParams.put("recCode",queryParams_recCode);}else{serachParams.put("recCode",null);}
		if(queryParams_cardedNumber != null && queryParams_cardedNumber.trim().length() > 0){serachParams.put("cardedNumber",queryParams_cardedNumber);}else{serachParams.put("cardedNumber",null);}
		serachParams.put("departid",departid);

		if(queryParams_sort 		!= null && queryParams_sort.trim().length() 		> 0){
			if("userName".equals(queryParams_sort)){
				queryParams_sort = "username";
			}else if("recCode".equals(queryParams_sort)){
				queryParams_sort = "rec_code";
			}else if("realName".equals(queryParams_sort)){
				queryParams_sort = "realName";
			}else if("cardedNumber".equals(queryParams_sort)){
				queryParams_sort = "carded_Number";
			}
			if("username".equals(queryParams_sort) || "rec_code".equals(queryParams_sort) || "realName".equals(queryParams_sort) || "carded_Number".equals(queryParams_sort)){
				serachParams.put("sort",queryParams_sort);
			}else{
				serachParams.put("sort",null);
			}
		}
		if(queryParams_order		!= null && queryParams_order.trim().length() 		> 0){
			if("asc".equals(queryParams_order) || "desc".equals(queryParams_order)){serachParams.put("order",queryParams_order);}else{serachParams.put("order","asc");}
		}
		try{
			serachParams.put("startIndex",(Integer.parseInt(queryParams_page)-1)*Integer.parseInt(queryParams_rows));
			serachParams.put("endIndex",Integer.parseInt(queryParams_rows));
		}catch (Exception e){
			serachParams.put("startIndex",1);
			serachParams.put("endIndex","10");
		}
		int count = reccodeService.usersCount(serachParams);	//当前查询总条数
		List<UserRecCodeEntity> users = reccodeService.users(serachParams);
		dataGrid.setTotal(count);
		dataGrid.setResults(users);
		TagUtil.datagrid(response, dataGrid);
	}
	//----

    /**
     * 获取机构树-combotree
     * @param request
     * @return
     */
    @RequestMapping(params = "getOrgTree")
    @ResponseBody
    public List<ComboTree> getOrgTree(HttpServletRequest request) {
//        findHql不能处理is null条件
//        List<TSDepart> departsList = systemService.findHql("from TSPDepart where TSPDepart.id is null");
        List<TSDepart> departsList = systemService.findByQueryString("from TSDepart where TSPDepart.id is null");
        List<ComboTree> comboTrees = new ArrayList<ComboTree>();
        ComboTreeModel comboTreeModel = new ComboTreeModel("id", "departname", "TSDeparts");
        comboTrees = systemService.ComboTree(departsList, comboTreeModel, null, true);
        return comboTrees;
    }

    /**
     * 添加 用户到组织机构 的页面  跳转
     * @param req request
     * @return 处理结果信息
     */
    @RequestMapping(params = "goAddUserToOrg")
    public ModelAndView goAddUserToOrg(HttpServletRequest req) {
        req.setAttribute("orgId", req.getParameter("orgId"));
        return new ModelAndView("system/depart/noCurDepartUserList");
    }
    /**
     * 获取 除当前 组织之外的用户信息列表
     * @param request request
     * @return 处理结果信息
     */
    @RequestMapping(params = "addUserToOrgList")
    public void addUserToOrgList(TSUser user, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        String orgId = request.getParameter("orgId");

        CriteriaQuery cq = new CriteriaQuery(TSUser.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, user);

        // 获取 当前组织机构的用户信息
        CriteriaQuery subCq = new CriteriaQuery(TSUserOrg.class);
        subCq.setProjection(Property.forName("tsUser.id"));
        subCq.eq("tsDepart.id", orgId);
        subCq.add();

        cq.add(Property.forName("id").notIn(subCq.getDetachedCriteria()));
        cq.add();

        this.systemService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }
    /**
     * 添加 用户到组织机构
     * @param req request
     * @return 处理结果信息
     */
    @RequestMapping(params = "doAddUserToOrg")
    @ResponseBody
    public AjaxJson doAddUserToOrg(HttpServletRequest req) {
    	String message = null;
        AjaxJson j = new AjaxJson();
        TSDepart depart = systemService.getEntity(TSDepart.class, req.getParameter("orgId"));
        saveOrgUserList(req, depart);
        message =  MutiLangUtil.paramAddSuccess("common.user");
//      systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        j.setMsg(message);

        return j;
    }
    /**
     * 保存 组织机构-用户 关系信息
     * @param request request
     * @param depart depart
     */
    private void saveOrgUserList(HttpServletRequest request, TSDepart depart) {
        String orgIds = oConvertUtils.getString(request.getParameter("userIds"));

        List<TSUserOrg> userOrgList = new ArrayList<TSUserOrg>();
        List<String> userIdList = extractIdListByComma(orgIds);
        for (String userId : userIdList) {
            TSUser user = new TSUser();
            user.setId(userId);

            TSUserOrg userOrg = new TSUserOrg();
            userOrg.setTsUser(user);
            userOrg.setTsDepart(depart);

            userOrgList.add(userOrg);
        }
        if (!userOrgList.isEmpty()) {
            systemService.batchSave(userOrgList);
        }
    }

    /**
     * 用户选择机构列表跳转页面
     *
     * @return
     */
    @RequestMapping(params = "departSelect")
    public String departSelect(HttpServletRequest req) {
    	
    	req.setAttribute("orgIds", req.getParameter("orgIds"));
    	
        return "system/depart/departSelect";
    }
    /**
     * 用户选择机构列表跳转页面
     *
     * @return
     */
    @RequestMapping(params = "departRatioSelect")
    public String departRatioSelect(HttpServletRequest req) {
    	
    	req.setAttribute("orgIds", req.getParameter("orgIds"));
    	req.setAttribute("aboutType", req.getParameter("aboutType"));
    	
        return "system/depart/departSelectRatioSetting";
    }
    /**
     * 角色显示列表
     *
     * @param response response
     * @param dataGrid dataGrid
     */
    @RequestMapping(params = "departSelectDataGrid")
    public void datagridRole(HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
        this.systemService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

	/**
	 * 导入功能跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","departController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(TSDepart tsDepart, HttpServletRequest request, HttpServletResponse response
			, DataGrid dataGrid, ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tsDepart, request.getParameterMap());
		cq.addOrder("orgCode", SortDirection.asc);
		List<TSDepart> tsDeparts = this.systemService.getListByCriteriaQuery(cq,false);
		/*List<TSDepart> finalTsDeparts = new ArrayList<TSDepart>();
		List<TSDepart> tsDeparts = systemService.getSession().createSQLQuery("select * from t_s_depart where length(org_code) = 3 order by org_code asc").addEntity(TSDepart.class).list();
		for(TSDepart tsDepart1:tsDeparts){
			finalTsDeparts.add(tsDepart1);
			String orgcode1 = tsDepart1.getOrgCode();
			List<TSDepart> tsDeparts1 = systemService.getSession().createSQLQuery("select * from t_s_depart where org_code like :orgcode and length(org_code)=6 order by org_code asc").addEntity(TSDepart.class).setString("orgcode",orgcode1+"%").list();
			for(TSDepart tsDepart2:tsDeparts1){
				finalTsDeparts.add(tsDepart2);
				String orgcode2 = tsDepart2.getOrgCode();
				List<TSDepart> tsDeparts2 = systemService.getSession().createSQLQuery("select * from t_s_depart where org_code like :orgcode and length(org_code)=9 order by org_code asc").addEntity(TSDepart.class).setString("orgcode",orgcode2+"%").list();
				for(TSDepart tsDepart3:tsDeparts2){
					finalTsDeparts.add(tsDepart3);
				}
			}
		}*/
		modelMap.put(NormalExcelConstants.FILE_NAME,"组织机构表");
		modelMap.put(NormalExcelConstants.CLASS,TSDepart.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("组织机构表列表", "导出人:"+ ResourceUtil.getSessionUserName().getRealName(),"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,tsDeparts);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 *
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(TSDepart tsDepart,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		modelMap.put(NormalExcelConstants.FILE_NAME,"组织机构表");
		modelMap.put(NormalExcelConstants.CLASS,TSDepart.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("组织机构表列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
				"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		int workinOld = 0;			//用于记录原数据的状态信息

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<TSDepart> tsDeparts = ExcelImportUtil.importExcel(file.getInputStream(),TSDepart.class,params);
				for (TSDepart tsDepart : tsDeparts) {
					String orgCode = tsDepart.getOrgCode();
					List<TSDepart> departs = systemService.findByProperty(TSDepart.class,"orgCode",orgCode);
					if(departs.size()!=0){
						TSDepart depart = departs.get(0);
						workinOld = depart.getWorking();
						MyBeanUtils.copyBeanNotNull2Bean(tsDepart,depart);	//这里会修改掉depart身上的值，而这个值没有被导出
						depart.setWorking(workinOld);
						systemService.saveOrUpdate(depart);
					}else {
						tsDepart.setOrgType(tsDepart.getOrgType().substring(0,1));
						//TSTypegroup ts = systemService.findByProperty(TSTypegroup.class,"typegroupcode","orgtype").get(0);
						//List<TSType> types = systemService.findByProperty(TSType.class,"id",ts.getId());
						//int len = 3;//每级组织机构得长度
						/*for(int i=0;i<types.size();i++){
							String typecode = types.get(i).getTypecode();
						}*/
						String orgcode = tsDepart.getOrgCode();
						String parentOrgCode = orgcode.substring(0,orgcode.length()-3);
						TSDepart parentDept = (TSDepart) systemService.getSession().createSQLQuery("select * from t_s_depart where ORG_CODE = :parentOrgCode")
								.addEntity(TSDepart.class)
								.setString("parentOrgCode",parentOrgCode)
								.list().get(0);
						tsDepart.setTSPDepart(parentDept);
						tsDepart.setWorking(1);
						userService.saveDepart(tsDepart,request.getSession().getId());
						//systemService.save(tsDepart);
					}
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}

	@RequestMapping(params = "getDepartInfo")
	@ResponseBody
	public AjaxJson getDepartInfo(HttpServletRequest request, HttpServletResponse response){
		
		AjaxJson j = new AjaxJson();
		
		String orgIds = request.getParameter("orgIds");
		
		String[] ids = new String[]{}; 
		if(StringUtils.isNotBlank(orgIds)){
			orgIds = orgIds.substring(0, orgIds.length()-1);
			ids = orgIds.split("\\,");
		}
		
		String parentid = request.getParameter("parentid");
		
		List<TSDepart> tSDeparts = new ArrayList<TSDepart>();
		
		StringBuffer hql = new StringBuffer(" from TSDepart t where 1=1 ");
		if(StringUtils.isNotBlank(parentid)){
			
			TSDepart dePart = this.systemService.getEntity(TSDepart.class, parentid);
			
			hql.append(" and TSPDepart = ?");
			tSDeparts = this.systemService.findHql(hql.toString(), dePart);
		} else {
			hql.append(" and t.orgType = ?");
			tSDeparts = this.systemService.findHql(hql.toString(), "1");
		}
		List<Map<String,Object>> dateList = new ArrayList<Map<String,Object>>();
		if(tSDeparts.size()>0){
			Map<String,Object> map = null;
			String sql = null;
			 Object[] params = null;
			for(TSDepart depart:tSDeparts){
				map = new HashMap<String,Object>();
				map.put("id", depart.getId());
				map.put("name", depart.getDepartname());
				
				if(ids.length>0){
					for(String id:ids){
						if(id.equals(depart.getId())){
							map.put("checked", true);
						}
					}
				}
				
				if(StringUtils.isNotBlank(parentid)){
					map.put("pId", parentid);
				} else{
					map.put("pId", "1");
				}
				//根据id判断是否有子节点
				sql = "select count(1) from t_s_depart t where t.parentdepartid = ?";
				params = new Object[]{depart.getId()};
				long count = this.systemService.getCountForJdbcParam(sql, params);
				if(count>0){
					map.put("isParent",true);
				}
				dateList.add(map);
			}
		}
		net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(dateList);
		j.setMsg(jsonArray.toString());
		return j;
	}

	@RequestMapping(params = "getDepartInfoForRatioSetting")
	@ResponseBody
	public AjaxJson getDepartInfoForRatioSetting(HttpServletRequest request, HttpServletResponse response){
		
		AjaxJson j = new AjaxJson();
		
		String orgIds = request.getParameter("orgIds");
		
		String aboutType = request.getParameter("aboutType");
		
		String[] ids = new String[]{}; 
		if(StringUtils.isNotBlank(orgIds)){
			orgIds = orgIds.substring(0, orgIds.length()-1);
			ids = orgIds.split("\\,");
		}
		
		String parentid = request.getParameter("parentid");
		
		List<TSDepart> tSDeparts = new ArrayList<TSDepart>();
		
		StringBuffer hql = new StringBuffer(" from TSDepart t where 1=1 ");
		if(StringUtils.isNotBlank(parentid)){
			
			TSDepart dePart = this.systemService.getEntity(TSDepart.class, parentid);
			
			if("1".equals(aboutType)){//承运商
				hql.append(" and TSPDepart = ? and service=1 ");
			}else if("2".equals(aboutType)){//物流服务商
				hql.append(" and TSPDepart = ? and carrier=1 ");
			}else{
				hql.append(" and TSPDepart = ?");
			}
			tSDeparts = this.systemService.findHql(hql.toString(), dePart);
		} else {
			if("1".equals(aboutType)){//承运商
				hql.append(" and t.orgType = ? and t.service=1");
			}else if("2".equals(aboutType)){//物流服务商
				hql.append(" and t.orgType = ? and t.carrier=1");
			}else{
				hql.append(" and t.orgType = ?");
			}
			tSDeparts = this.systemService.findHql(hql.toString(), "1");
		}
		List<Map<String,Object>> dateList = new ArrayList<Map<String,Object>>();
		if(tSDeparts.size()>0){
			Map<String,Object> map = null;
			String sql = null;
			 Object[] params = null;
			for(TSDepart depart:tSDeparts){
				map = new HashMap<String,Object>();
				map.put("id", depart.getId());
				map.put("name", depart.getDepartname());
				
				if(ids.length>0){
					for(String id:ids){
						if(id.equals(depart.getId())){
							map.put("checked", true);
						}
					}
				}
				
				if(StringUtils.isNotBlank(parentid)){
					map.put("pId", parentid);
				} else{
					map.put("pId", "1");
				}
				//根据id判断是否有子节点
				if("1".equals(aboutType)){
					sql = "select count(1) from t_s_depart t where t.parentdepartid = ? and t.isService=1";
				}else if("2".equals(aboutType)){
					sql = "select count(1) from t_s_depart t where t.parentdepartid = ? and t.isCarrier=1";
				}else{
					sql = "select count(1) from t_s_depart t where t.parentdepartid = ?";
				}
				params = new Object[]{depart.getId()};
				long count = this.systemService.getCountForJdbcParam(sql, params);
				if(count>0){
					map.put("isParent",true);
				}
				dateList.add(map);
			}
		}
		net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(dateList);
		j.setMsg(jsonArray.toString());
		return j;
	}

	/***
	 * 文件上传，这里主要是上传图片，图片上传后返回图片在服务器的位置
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "upload", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> upload(MultipartHttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> resultJson = new HashMap<String, Object>();
		resultJson.put("status","1");
		resultJson.put("message","文件上传成功");
		List<String> urls = new ArrayList<String>();
		logger.info("文件上传开始------------------------------------------>");
		Iterator<String> itr = request.getFileNames();
		MultipartFile mpf = null;
		while (itr.hasNext()) {
			logger.info("upload-》2.1 get next MultipartFile");
			mpf = request.getFile(itr.next());
			//System.out.println(mpf.getOriginalFilename() + " uploaded! " + files.size());
			logger.info("2.2 if files > 10 remove the first from the list");
			logger.info("2.3 create new fileMeta");
			long kb = mpf.getSize() / 1024;
			if(kb >= 5120){ //5M  = 5120
				resultJson.put("status","-2");
				resultJson.put("message","文件不能大于5M");
				resultJson.put("urls",urls);
				resultJson.put("msg","true");
				logger.info("文件大于5M 上传失败");
				logger.info("文件上传结束------------------------------------------>");
				return resultJson;
			}
			mpf.getContentType();
			try {
				String path ="upload/";
				String saveFileName = getFileUploadName();
				String realPath = request.getSession().getServletContext().getRealPath("/") + "/" + path ;// 文件的硬盘真实路径
				logger.info("upload-》文件的硬盘真实路径"+realPath);
				String savePath = realPath + saveFileName+mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf("."));// 文件保存全路径
				logger.info("upload-》文件保存全路径"+savePath);
				FileCopyUtils.copy(mpf.getBytes(), new File(savePath));
				logger.info("copy file to local disk (make sure the path e.g. D:/temp/files exists)");
				urls.add(path + saveFileName+mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf(".")-1));
			} catch (IOException e) {
				resultJson.put("status","-1");
				resultJson.put("message","文件上传异常");
				e.printStackTrace();
			}
			logger.info("2.4 add to files");
		}
		resultJson.put("urls",urls);
		resultJson.put("msg","true");
		logger.info("文件上传结束------------------------------------------>");
		return resultJson;
	}


	/***
	 * 获取是随机上传文件名
	 *
	 * @return
	 */
	public String getFileUploadName(){
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		return sdf.format(date)+(Math.random() + "").substring(2, 8);
	}


	/**
	 * 部门列表页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "shuntDepart")
	public ModelAndView shuntDepart() {
		return new ModelAndView("system/depart/shuntDepartList");
	}
	/**
	 * easyuiAJAX请求数据
	 *
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "shuntDatagrid")
	public void shuntDatagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		//CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
		Map map = new HashMap();
		int page = dataGrid.getPage();
		int pageSize = dataGrid.getRows();
		int begin = (page - 1)*pageSize;
		map.put("begin", begin);
		map.put("pageSize", pageSize);

		dataGrid.setTotal(departService.getDepartCount());
		dataGrid.setResults(departService.getDepartVOList(map));
		//this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除部门：
	 * <ul>
	 *     组织机构下存在子机构时
	 *     <li>不允许删除 组织机构</li>
	 * </ul>
	 * <ul>
	 *     组织机构下存在用户时
	 *     <li>不允许删除 组织机构</li>
	 * </ul>
	 * <ul>
	 *     组织机构下 不存在子机构 且 不存在用户时
	 *     <li>删除 组织机构-角色 信息</li>
	 *     <li>删除 组织机构 信息</li>
	 * </ul>
	 * @return 删除的结果信息
	 */
	@RequestMapping(params = "delShunt")
	@ResponseBody
	public AjaxJson delShunt(HttpServletRequest request) {
		String departId = request.getParameter("id");
		String message = "删除成功";
		AjaxJson j = new AjaxJson();
		net.lahuobao.shunting.entity.shunt.TSDepart depart = departService.selectByPrimaryKey(departId);
		if(depart==null){
			return j;
		}
		if(departService.getDepartsCounts(departId)==0){
			if(departService.getDepartUserCount(departId)==0){
				departService.deleteDepart(depart.getId());
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}else{
				message = "存在用户成员不能删除";
			}
		}else {
			message = "存在下级机构不能删除";
		}
		j.setMsg(message);
		return j;
	}
	/**
	 * 添加部门
	 *
	 * @return
	 */
	@RequestMapping(params = "saveShunt")
	@ResponseBody
	public AjaxJson saveShunt(HttpServletRequest request) {
		String message = null;

		AjaxJson j = new AjaxJson();
		try {
			Map map = getRequestParam(request);
			String localMaxCode  = getMaxLocalCode(null);
			map.put("orgCode",YouBianCodeUtil.getNextYouBianCode(localMaxCode));
			message = "门店添加成功";
			if(map.containsKey("id")){
				String id = (String)map.get("id");
				if(StringUtils.isNotEmpty(id)){
					net.lahuobao.shunting.entity.shunt.TSDepart depart = departService.selectByPrimaryKey(id);
					if(depart==null){
						departService.saveDepart(map);
					}else{
						String departname = (String)map.get("departname");
						String departType = (String)map.get("departType");
						if(depart.getDepartname()!=null &&
								!depart.getDepartname().equals(departname)){
							int count = departService.getDepartNumByTypeAndName(departname,Integer
									.valueOf(departType));
							if(count != 0){
								throw new Exception("组织名已存在");
							}
						}
						departService.updateDepart(depart,map);
						message = "门店修改成功";
					}
				}else{
					departService.saveDepart(map);
				}
			}else{
				departService.saveDepart(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
			j.setMsg("保存失败");
			return j;
		}

		j.setMsg(message);
		return j;
	}
	@RequestMapping(params = "addShunt")
	public ModelAndView addShunt(HttpServletRequest req) {
		List<DepartVO> departsZones = departService.getDepartVOListByType(2);
		ModelAndView model = new ModelAndView("system/depart/departAdd");
		model.addObject("departsZones",departsZones);
		return model;
	}
	@RequestMapping(params = "departCount")
	@ResponseBody
	public AjaxJson searchDepart(String departName,String departType,String id){
		AjaxJson j = new AjaxJson();
		if(StringUtils.isNotEmpty(id)){
			j.setSuccess(true);
			return j;
		}
		j.setSuccess(false);
		if(StringUtil.isNotEmpty(departType)){
			int count = departService.getDepartNumByTypeAndName(departName, Integer.valueOf(departType));
			if (count == 0) {
				j.setSuccess(true);
				j.setMsg("名称可用");
				return j;
			}
		}
		return j;
	}

	@RequestMapping(params = "editShunt")
	public ModelAndView editShunt(HttpServletRequest req) {
		String departId = req.getParameter("id");
		net.lahuobao.shunting.entity.shunt.TSDepart depart = new net.lahuobao.shunting.entity.shunt.TSDepart();
		if(StringUtil.isNotEmpty(departId)) {
			depart = departService.selectByPrimaryKey(departId);
		}
		List<DepartVO> departsZones = departService.getDepartVOListByType(2);
		ModelAndView model = new ModelAndView("system/depart/departAdd");
		model.addObject("depart",depart);
		model.addObject("departsZones",departsZones);
		return model;
	}
	public Map getRequestParam(HttpServletRequest request){
		Map map = new HashMap();
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements()){
			String name = names.nextElement();
			map.put(name,request.getParameter(name));
		}
		return map;
	}

	/**
	 * 转派选择门店列表跳转页面
	 *
	 * @return
	 */
	@RequestMapping(params = "shuntDepartSelect")
	public String shuntDepartSelect(HttpServletRequest req) {
		return "net/lahuobao/shunting/shunt/shuntDepartSelect";
	}

	@RequestMapping(params = "getShuntDepartInfo")
	@ResponseBody
	public AjaxJson getShuntDepartInfo(HttpServletRequest request, HttpServletResponse response){

		AjaxJson j = new AjaxJson();


		String parentid = request.getParameter("parentid");

		List<TSDepart> tSDeparts = new ArrayList<TSDepart>();

		StringBuffer hql = new StringBuffer(" from TSDepart t where 1=1 ");
		//只查门店或区域
		hql.append(" and t.departType in(1,2)");
		if(StringUtils.isNotBlank(parentid)){

			TSDepart dePart = this.systemService.getEntity(TSDepart.class, parentid);

			hql.append(" and TSPDepart = ?");
			tSDeparts = this.systemService.findHql(hql.toString(), dePart);
		} else {
			hql.append(" and t.orgType = ?");
			tSDeparts = this.systemService.findHql(hql.toString(), "1");
		}
		List<Map<String,Object>> dateList = new ArrayList<Map<String,Object>>();
		if(tSDeparts.size()>0){
			Map<String,Object> map = null;
			String sql = null;
			Object[] params = null;
			for(TSDepart depart:tSDeparts){
				map = new HashMap<String,Object>();
				map.put("id", depart.getId());
				map.put("name", depart.getDepartname());
				if(StringUtils.isNotBlank(parentid)){
					map.put("pId", parentid);
				} else{
					map.put("pId", "1");
				}
				//根据id判断是否有子节点
				sql = "select count(1) from t_s_depart t where t.parentdepartid = ?";
				params = new Object[]{depart.getId()};
				long count = this.systemService.getCountForJdbcParam(sql, params);
				if(count>0){
					map.put("isParent",true);
				}
				//部门类型 0-部门 1-门店,只能选择门店
				if(depart.getDepartType()==1){
					map.put("nocheck",false);
				}else{
					map.put("nocheck",true);
				}
				dateList.add(map);
			}
		}
		net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(dateList);
		j.setMsg(jsonArray.toString());
		return j;
	}

	private synchronized String getMaxLocalCode(String parentCode){
		if(oConvertUtils.isEmpty(parentCode)){
			parentCode = "";
		}
		int localCodeLength = parentCode.length() + YouBianCodeUtil.zhanweiLength;
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT org_code FROM t_s_depart");

		if(ResourceUtil.getJdbcUrl().indexOf(JdbcDao.DATABSE_TYPE_SQLSERVER)!=-1){
			sb.append(" where LEN(org_code) = ").append(localCodeLength);
		}else{
			sb.append(" where LENGTH(org_code) = ").append(localCodeLength);
		}

		if(oConvertUtils.isNotEmpty(parentCode)){
			sb.append(" and  org_code like '").append(parentCode).append("%'");
		}

		sb.append(" ORDER BY org_code DESC");
		List<Map<String, Object>> objMapList = systemService.findForJdbc(sb.toString(), 1, 1);
		String returnCode = null;
		if(objMapList!=null && objMapList.size()>0){
			returnCode = (String)objMapList.get(0).get("org_code");
		}

		return returnCode;
	}
}
